import { getuUserProfile, postLogin } from '@/api/user'
import { getToken, setToken } from '@/utils/auth'

const state = {
  token: getToken() || '',
  userInfo: JSON.parse(localStorage.getItem('obj')) || {}
}

const mutations = {
  setToken(state, token) {
    //  存储到 vuex
    state.token = token
    // 存储到 Cookie
    setToken(token)
  },
  getInfo(state, userInfo) {
    state.userInfo = userInfo
    localStorage.setItem('obj', JSON.stringify(userInfo))
  }
}

const actions = {
  async loginActions(context, data) {
    // 发送登录请求
    const res = await postLogin(data)
    console.log(res)
    // console.log(res.data.user)
    console.log(res.data.token.token)
    const token = res.data.token.token
    const userInfo = res.data.user
    context.commit('setToken', token)
    context.commit('getInfo', userInfo)
  },
  logout(context) {
    context.commit('setToken', '')
  },
  async getProfile(context) {
    const res = await getuUserProfile()
    console.log(res)
  }
}
export default {
  namespaced: true,
  state,
  mutations,
  actions
}

